package com.xiaochi.subject.common.config;

import com.xiaochi.subject.common.context.LoginContextHolder;
import org.springframework.core.task.TaskDecorator;

import java.util.Map;



/**
 * 装饰器
 *
 * 实现线程池里的线程上下文传递
 *
 * @author zqx
 * @since 2024/9/6
 */
public class ThreadTaskDecorator implements TaskDecorator {


    @Override
    public Runnable decorate(Runnable runnable) {
        Map<String, Object> threadLocalMap = LoginContextHolder.getThreadLocalMap();
        return () -> {
            try {
                Object id = threadLocalMap.get("loginId");
                LoginContextHolder.setThreadLocal("loginId",id);
                runnable.run();
            }finally {
                //注意 因为线程池的核心线程是复用，所以一直都是强引用，不会被gc回收，所以防止内存泄露，需要清除线程池中，子线程的上下文
                LoginContextHolder.remove();
            }
        };
    }
}
